import { defineConfig, loadEnv } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import copy from 'rollup-plugin-copy'
import path from 'path'
import fs from 'fs'
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  return {
    base: env.NODE_ENV === 'development' ? './' : './',
    envDir: './',
    build: {
      target: 'esnext',
      cssCodeSplit: true,
      assetsInlineLimit: 10240,
      reportCompressedSize: true,
      outDir: './dist/',
    },
    plugins: [
      env.NODE_ENV !== 'development'
        ? copy({
            targets: [
              {
                src: path.resolve(__dirname, '/static'),
                dest: `/dist/${__dirname}/`,
              },
            ],
            hook: 'writeBundle',
          })
        : void 0,
      uni(),
    ],
    server: {
      port: 3000,
      host: true,
      https: {
        cert: fs.readFileSync(path.join(__dirname, 'src/ssl/cert.crt')),
        key: fs.readFileSync(path.join(__dirname, 'src/ssl/cert.key')),
      },
      open: 'index.html',
      proxy: {
        [env.VITE_PROXY_KEY as string]: {
          target: env.VITE_BASE_API_URL,
          changeOrigin: true,
          rewrite: (path) => {
            return path.replace(env.VITE_PROXY_KEY, '')
          },
          bypass(req, res, options) {
            let reqUrl = options.rewrite!(req.url as string)
            let targetUrl = options.target as string
            const proxyUrl = new URL(reqUrl, targetUrl)?.href || ''
          },
        },
        '/console': {
          target: env.VITE_BASE_API_URL,
          changeOrigin: true,
          rewrite: (path) => {
            return path
          },
          bypass(req, res, options) {
            let reqUrl = options.rewrite!(req.url as string)
            let targetUrl = options.target as string
            const proxyUrl = new URL(reqUrl, targetUrl)?.href || ''
          },
        },
      },
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        '~@': path.resolve(__dirname, 'src/static'),
        '~com': path.resolve(__dirname, 'src/components'),
      },
    },
    define: {
      'process.env': env,
    },
    envPrefix: ['VITE_', 'NODE_ENV'],
    sourcemap: false,
    chunkSizeWarningLimit: 500,
  }
})
